import 'dart:_http';

import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:member_center_sdk_example/interfaces/IDemoApi.dart';
import 'package:member_center_sdk_example/models/member.dart';
import 'package:member_center_sdk_example/utils/device_helper.dart';

class _ServiceException implements Exception {
  final String message;

  const _ServiceException(this.message);
}

class DemoService extends IDemoApi {
  //final _baseUrl = 'http://res.test.hsq168.co:9200/';
  final _baseUrl = 'http://192.168.1.8:9200/';
  static final DemoService _internal = DemoService.internal();

  factory DemoService() => _internal;

  DemoService.internal();

  Future<T> request<T, M>(String url,
      {Map<String, dynamic> data, M convert(dynamic item)}) async {
    try {
      var response = await Dio().request(_baseUrl + url,
          data: data,
          options: RequestOptions(
              contentType: ContentType.json,
              method: data == null ? "GET" : "POST"));
      if (response.statusCode == 200) {
        if (response.data["Success"] == true) {
          var result = response.data["Result"];
          if (result.runtimeType.toString().startsWith("List<")) {
            var list =
                (result as List<dynamic>).map((item) => convert(item)).toList();
            return list as T;
          } else {
            return convert(result) as T;
          }
        } else {
          throw _ServiceException(response.data["Message"]);
        }
      } else {
        throw _ServiceException('服务器错误');
      }
    } on _ServiceException catch (e) {
      Fluttertoast.showToast(msg: e.message);
      throw e;
    } on Exception catch (e) {
      Fluttertoast.showToast(msg: "网络请求发生错误");
      throw e;
    }
  }

  Future<int> buy(int productId, int memberId) async {
    var result = await request<int, int>('member/Buy',
        data: {"memberId": memberId, "productId": productId},
        convert: (dynamic item) => int.parse(item["OrderId"].toString()));
    return result;
  }

  @override
  Future<Member> register(String smsKey, String code) async {
    var result = await request<Member, Member>('home/register',
        data: {"smsKey": smsKey, "code": code},
        convert: (dynamic item) => Member.fromMap(item));
    return result;
  }

  @override
  Future<String> sendSms(String phone) async {
    var result = await request<String, String>('home/register',
        data: {"phone": phone, "deviceId": await DeviceHelper.getDeviceId()},
        convert: (dynamic item) => item.toString());
    return result;
  }
}
